/*
 * @Author: xiehangyun 
 * @Date: 2025-05-10 18:19:41 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-08-01 14:01:30
 */

import { Loading, More } from "@nutui/icons-react-taro";
import { Button, Col, ConfigProvider, Divider, InputNumber, NavBar, Popover, Row, Swipe, SwipeInstance } from '@nutui/nutui-react-taro'; // 添加单选按钮和下拉菜单组件的导入
import { Image, Text, View, } from '@tarojs/components';
import Taro, { useDidHide, useDidShow } from "@tarojs/taro";
import clsx from 'clsx';
import { autorun, toJS } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import goodsBaseApi from 'src/api/goodsBaseApi';
import CustomHeader from 'src/components/CustomHeader/CustomHeader';
import CustomTabBar from 'src/components/CustomTabBar/CustomTabBar';
import MyEmpty from 'src/components/MyEmpty/MyEmpty';
import MyPopup from "src/components/MyPopup/MyPopup";
import confirmOrderStore from "src/subPages/ConfirmOrder/ConfirmOrderStore";
import toDesign from 'src/subPages/Design/designComponent/toDesign';
import goGoodsDetail from 'src/subPages/GoodsDetail/goGoodsDetail';
import utils from 'src/utils/utils';
import { ShopCarData } from 'types/type';
import styles from "./shoppingCart.module.less";
import shoppingCartStore from './shoppingCartStore';

import sizeTableSVG from "./imgs/sizeTable.svg";
import MyScrollView from "src/components/MyScrollView/MyScrollView";
import utilsStore from "src/utils/utilsStore";

interface Iprops {
    children?: ReactNode
}

// 购物车页面
export default function ShoppingCart(props: Iprops) {

    const [list, setList] = useState<Array<ShopCarData>>([]);

    const dom = useRef<HTMLDivElement | null>(null);
    const [data, setData] = useState({});
    const [showPopoverId, setShowPopoverId] = useState(0);

    const [selectedItemIds, setSelectedItemIds] = useState<Array<number>>([]); // 添加状态以跟踪选中的商品
    const [isManaging, setIsManaging] = useState(false); // 管理模式状态
    const [showSizePopup, setShowSizePopup] = useState(false); // 弹出层显示状态
    const [selectedSize, setSelectedSize] = useState(''); // 当前选中的尺码
    const [currentShopCarId, setCurrentShopCarId] = useState(0); // 当前选中的商品id

    const [totalPrice, setTotalPrice] = useState<number>(0);
    const [sizes, setSizes] = useState<Array<string>>([]);
    const [sizeRecommendImageUrl, setSizeRecommendImageUrl] = useState<string>('');


    const selectAll = (selectedItemIds.length > 0 && list.filter(item => {
        return !(item.productIfDel ||
            item.productIfPutaway ||
            item.productNegativeIfDel ||
            item.productNegativeIfPutaway)
    }).length <= selectedItemIds.length);

    useEffect(() => autorun(() => {
        setList(toJS(shoppingCartStore.list));
        setSelectedItemIds(toJS(shoppingCartStore.selectedItemIds));
        setTotalPrice(shoppingCartStore.totalPrice);
    }, { delay: 30 }), []);

    useDidShow(() => {
        shoppingCartStore.getList();
    });

    /**
     * 切换全选状态
     */
    const toggleSelectAll = () => {
        if (selectAll) {
            shoppingCartStore.setSelectedItemIds([]);
        } else {
            // 全选没有过期的
            shoppingCartStore.setSelectedItemIds(list
                .filter(item => {
                    return !(item.productIfDel ||
                        item.productIfPutaway ||
                        item.productNegativeIfDel ||
                        item.productNegativeIfPutaway);
                }).map(item => item.id));
        }
    };

    /**
     * 处理单个商品的选择/取消选择
     * @param id 商品ID
     */
    const handleSelectItem = (id: number) => {
        if (selectedItemIds.includes(id)) {
            const newSelectedItemIds = selectedItemIds.filter(selectedItemId => selectedItemId !== id);
            shoppingCartStore.setSelectedItemIds(newSelectedItemIds);
        } else {
            shoppingCartStore.setSelectedItemIds([...selectedItemIds, id]);
        }
    };

    /**
     * 切换管理状态（编辑/完成）
     * 控制是否显示删除按钮和规格选择
     */
    const toggleManaging = () => {
        setIsManaging(!isManaging);
        shoppingCartStore.cancelAllSelect();
    };

    const handleDelete = async (ids?: Array<number>) => {
        Taro.showModal({
            title: '提示',
            content: '确定要删除选中的商品吗？',
            success: async (res) => {
                if (res.confirm) {
                    await shoppingCartStore.delete(ids ? ids.join(',') : selectedItemIds.join(','));
                    setIsManaging(false);
                    shoppingCartStore.cancelAllSelect();
                }
            }
        });
    };

    // const sysInfo = Taro.getSystemInfoSync();
    // const menuButtonInfo = Taro.getMenuButtonBoundingClientRect();
    // const statusBarHeight = sysInfo.statusBarHeight || 0; // 状态栏高度
    // const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2; // 导航栏总高度

    /**
     * 处理尺码选择
     * @param size 选中的尺码
     */
    const handleSizeChange = (size: string) => {
        setSelectedSize(size);
    };

    /**
     * 显示尺码选择弹窗
     * @param productNegativeId 商品负面ID，用于获取尺码数据
     */
    const showSize = (productNegativeId: number) => {
        goodsBaseApi.getProductNegativeById(productNegativeId).then(goodsBaseData => {
            setSizes(goodsBaseData.data.sizes.filter(s => s.enable).map(s => s.name));
            setShowSizePopup(true);
        });
    };

    // 计算每行的高度
    // const getGoodsItemHeight = () => {
    //     // 375 - 150
    //     // 430 - 170
    //     // return 170;
    //     return 150 + (((170 - 150) / (430 - 375)) * (sysInfo.windowWidth - 375));
    // };

    // console.log("windowWidth", sysInfo.windowWidth);

    useDidHide(() => {
        Taro.setStorageSync("productId", '');
    });

    const productId = Taro.getStorageSync("productId");
    console.log("productId", productId);

    const swipeRefMap: Map<number, SwipeInstance> = new Map();

    return (
        <View className={styles.shoppingCart} >
            {/* 自定义头部 */}
            <CustomHeader
                showBack={Boolean(productId)}
                onBack={() => {
                    if (Boolean(productId)) {
                        goGoodsDetail(productId);
                    }
                }}
            >
                <NavBar
                    className={styles.navBar}
                    back={
                        <Text className={styles.titleText} >购物车</Text>
                    }
                    right={
                        list.length > 0 &&
                        <Text className={styles.manager} onClick={toggleManaging}>
                            {isManaging ? '完成' : '管理'}
                        </Text>
                    }
                />
            </CustomHeader >

            {!shoppingCartStore.loadding && list.length === 0 &&
                <MyEmpty
                    style={{
                        marginTop: "16vh"
                    }}
                    description="购物车空空如也"
                    actions={[
                        {
                            text: '去逛逛',
                            onClick: () => {
                                Taro.switchTab({
                                    url: '/pages/Category/Category'
                                })
                            }
                        }
                    ]}
                />
            }
            {/* {shoppingCartStore.loadding && <Loading />} */}
            {/* 商品列表 */}
            {
                list.length > 0 &&
                <MyScrollView
                    className={styles.goodsList}
                    style={{
                        height: utilsStore.containerHeight - utils.rpx2px(180)
                    }}
                >
                    {/* <View className={styles.goodsList}> */}
                    {
                        list.map((item: ShopCarData, index) => {

                            // 是否过期商品，过期商品显示灰色样式提示信息
                            const isExpired =
                                item.productIfDel ||
                                item.productIfPutaway ||
                                item.productNegativeIfDel ||
                                item.productNegativeIfPutaway;

                            return (
                                <Swipe
                                    onTouchStart={(e) => {
                                        swipeRefMap.forEach((value, key) => {
                                            if (index !== key) {
                                                value.close();
                                            }
                                        });
                                    }}
                                    ref={ref => {
                                        if (ref) {
                                            swipeRefMap.set(index, ref);
                                        }
                                    }}
                                    key={item.id}
                                    style={{
                                        background: 'none'
                                    }}
                                    rightAction={
                                        <div
                                            style={{
                                                height: 'inherit',
                                                width: '60px',
                                                display: 'flex',
                                                fontSize: '12px',
                                            }}
                                        >
                                            <>
                                                <SwipeBtn
                                                    style={{
                                                        background: '#FA2C19',
                                                        color: '#FFF',
                                                    }}
                                                    onClick={() => handleDelete([item.id])}
                                                >
                                                    删除
                                                </SwipeBtn>
                                            </>
                                        </div>
                                    }
                                >
                                    <Row className={clsx(
                                        styles.cartItem,
                                        (!isManaging && isExpired) && styles.expiredItem
                                    )}>

                                        {
                                            isExpired ?
                                                <Text className={styles.expiredTag}>已过期</Text>
                                                :
                                                <Popover
                                                    visible={true}
                                                    location='bottom'
                                                    style={{
                                                        marginInlineEnd: '200rpx',
                                                    }}
                                                    className={clsx(styles.popover, (showPopoverId === item.id) && styles.show)}
                                                    list={[
                                                        { key: '1', name: '修改设计', className: styles.popoverBtn },
                                                        { key: '2', name: '修改规格', className: styles.popoverBtn },
                                                        { key: '3', name: '复制设计', className: styles.popoverBtn },
                                                    ]}
                                                    onSelect={(option) => {
                                                        console.log('选中项:', option);
                                                        switch (option.name.trim()) {
                                                            case "修改设计":
                                                                toDesign({
                                                                    productId: item.productId,
                                                                    productNegativeId: item.productNegativeId,
                                                                    productDesign: item.productDesign,
                                                                    designName: item.designName,
                                                                    size: item.size,
                                                                    color: item.productDesign.color,
                                                                    colorValue: item.productDesign.colorValue,
                                                                    needupload: true
                                                                })
                                                                break;
                                                            case "修改规格":
                                                                setCurrentShopCarId(item.id);
                                                                showSize(item.productNegativeId);
                                                                setSelectedSize(item.size);
                                                                setSizeRecommendImageUrl(item.sizeRecommendImageUrl);
                                                                break;

                                                            case "复制设计":
                                                                shoppingCartStore.copyShopCart(item.id);
                                                                break;

                                                            default:
                                                                break;
                                                        }

                                                    }}
                                                    onClick={() => {
                                                        setShowPopoverId((showPopoverId === item.id) ? 0 : item.id);
                                                    }}
                                                >
                                                    <More className={styles.more} />
                                                </Popover>
                                        }

                                        <Row
                                            onClick={() => {
                                                if (isManaging || !isExpired) {
                                                    handleSelectItem(item.id);
                                                }
                                            }}
                                        >
                                            <Col span={2} >
                                                <View
                                                    className={styles.itemRadio}
                                                    style={{ marginTop: '30px' }}
                                                >
                                                    <View className={clsx(styles.itemRadioInner, selectedItemIds.includes(item.id) && styles.active)} >
                                                    </View>
                                                </View>

                                            </Col>
                                            <Col span={8} style={{ position: 'relative' }}>
                                                <Image
                                                    src={utils.ossSuffix(item.productDesign.thumbs[0], utils.rpx2px(260))}
                                                    className={styles.itemImage}
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        e.preventDefault();
                                                        if (item.productDesign.thumbs.length > 1) {
                                                            Taro.previewImage({
                                                                urls: [
                                                                    utils.ossSuffix(item.productDesign.thumbs[0], 1024),
                                                                    utils.ossSuffix(item.productDesign.thumbs[1], 1024)
                                                                ]
                                                            });
                                                        }
                                                    }}
                                                />
                                                {
                                                    item.productDesign.thumbs[1] &&
                                                    <Image
                                                        src={utils.ossSuffix(item.productDesign.thumbs[1], utils.rpx2px(80))}
                                                        className={styles.perImg}
                                                    />
                                                }
                                            </Col>
                                            <Col span={14} className={styles.itemDetails}>
                                                <Text className={styles.itemName}>{item.designName}</Text>
                                                <Text className={styles.itemInfo}>编码: {item.utStyleNum}</Text>
                                                {
                                                    /^[\u4e00-\u9fa5]+$/.test(item.color) &&
                                                    <Text className={styles.itemInfo}>颜色: {item.color}</Text>
                                                }
                                                <Text className={styles.itemInfo}>
                                                    尺码: {item.size}
                                                    <Text
                                                        className={styles.uploadSize}
                                                        onClick={(e) => { // 点击时显示弹出层
                                                            e.stopPropagation();
                                                            e.preventDefault();
                                                            setCurrentShopCarId(item.id);
                                                            showSize(item.productNegativeId);
                                                            setSelectedSize(item.size);
                                                            setSizeRecommendImageUrl(item.sizeRecommendImageUrl);
                                                        }}
                                                    >
                                                        修改
                                                    </Text>
                                                </Text>
                                            </Col>
                                        </Row>

                                        <Row>
                                            <Col span={2}></Col>
                                            <Col span={12}>
                                                <View className={styles.itemActions}>
                                                    <Text className={styles.itemPrice}>
                                                        <Text className={styles.unit} >单价:</Text>
                                                        ¥{item.pagePrice}
                                                    </Text>
                                                </View>
                                            </Col>
                                            <Col span={9}>
                                                <ConfigProvider
                                                    theme={{
                                                        nutuiInputnumberButtonWidth: '24px',
                                                        nutuiInputnumberButtonHeight: '24px',
                                                        nutuiInputnumberButtonBorderRadius: '2px',
                                                        nutuiInputnumberButtonBackgroundColor: `#f4f4f4`,
                                                        nutuiInputnumberInputHeight: '24px',
                                                        nutuiInputnumberInputMargin: '0 2px'
                                                    }}>
                                                    <InputNumber
                                                        value={item.productNumber}
                                                        step={1}
                                                        digits={0}
                                                        className={styles.num}
                                                        onChange={(value: number) => {
                                                            if (value) {
                                                                shoppingCartStore.changeProductNumber(item.id, value);
                                                            }
                                                        }}
                                                    />
                                                </ConfigProvider>
                                            </Col>
                                        </Row>
                                    </Row>
                                </Swipe>
                            );
                        })
                    }
                    {/* <Divider
                            style={{
                                borderStyle: 'solid',
                                width: '50%',
                                margin: '0rpx auto',
                                padding: '30rpx 0',
                            }}
                        >
                            到底了
                        </Divider> */}
                    {/* </View> */}
                </MyScrollView>
            }

            {/* 自定义底部 */}
            <CustomTabBar >
                <Row className={styles.footer} >
                    <Col span={8} >
                        <View className={styles.selectAll} onClick={toggleSelectAll}>
                            <View
                                className={styles.itemRadio}
                            >
                                <View className={clsx(styles.itemRadioInner, selectAll && styles.active)} >
                                </View>
                            </View>
                            全选
                        </View>
                    </Col>
                    <Col span={16} >
                        {isManaging ? (
                            <Button
                                type="warning"
                                className={styles.checkoutButton}
                                onClick={() => handleDelete()}
                            >
                                删除
                            </Button>
                        ) : (
                            <>
                                <Text className={styles.totalPriceLabel} >合计 : </Text>
                                <Text className={styles.totalPrice}>
                                    ¥{totalPrice}
                                </Text>
                                <Button
                                    type="warning"
                                    className={styles.checkoutButton}
                                    onClick={() => {
                                        const selectedItems = list.filter(item => selectedItemIds.includes(item.id));
                                        if (selectedItems.length === 0) {
                                            Taro.showToast({
                                                title: '请选择要结算的商品',
                                                icon: 'none'
                                            });
                                            return;
                                        }
                                        confirmOrderStore.setCoupon();
                                        Taro.navigateTo({
                                            url: `/subPages/ConfirmOrder/ConfirmOrder`,
                                        });
                                    }}
                                >
                                    去结算
                                </Button>
                            </>
                        )}
                    </Col>
                </Row>
            </CustomTabBar >

            {/* 弹出层 */}
            <MyPopup
                leftNode={
                    <Button
                        className={styles.sizeTableBtn}
                        onClick={() => {
                            Taro.previewImage({
                                urls: [utils.ossSuffix(utils.ossSuffix(sizeRecommendImageUrl), 1024)],
                            });
                        }}
                    >
                        <Image
                            className={styles.icon}
                            src={sizeTableSVG} />
                        尺码表
                    </Button>
                }
                open={showSizePopup}
                className={styles.sizeColorPopup}
                title={'选择尺码'}
                onClose={() => {
                    setShowSizePopup(false);
                }}
            >
                <View className={styles.title}>尺码</View>
                <View className={styles.sizeOptions}>
                    {sizes.map((size) => (
                        <Text
                            key={size}
                            className={clsx(styles.sizeOption, size === selectedSize && styles.selected)}
                            onClick={() => setSelectedSize(size)}
                        >
                            {size}
                        </Text>
                    ))}
                </View>

                <Button
                    type="primary"
                    block
                    className={styles.confirmButton}
                    onClick={() => {
                        shoppingCartStore.changeProductSize(currentShopCarId, selectedSize);
                        setShowSizePopup(false)
                    }} // 点击确认关闭弹出层
                >确定</Button>

            </MyPopup >

        </View >
    );
}



function SwipeBtn(props: React.HTMLAttributes<HTMLDivElement>) {

    const { style, children, className, ...otherProps } = props;

    return (
        <div
            {...otherProps}
            style={{
                width: '60px',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                borderRadius: '34rpx',
                ...style,
            }}
            className={className}
        >
            {/* <Del style={{ marginBottom: '8px' }} /> */}
            {children}
        </div>
    );

}